package cn.befory.common;

import lombok.extern.log4j.Log4j2;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolationException;
import java.util.List;

/**
 * 异常处理器
 */
@RestControllerAdvice
@Log4j2
public class SysExHandler {

    @ExceptionHandler(MissingServletRequestParameterException.class)
    public ResponseEntity<Result> missingServletRequestParameterException(MissingServletRequestParameterException e) {
        return ResponseEntity.ok(Result.error(ExCode.E_90001));
    }

    @ExceptionHandler(value = {MethodArgumentNotValidException.class})
    public ResponseEntity<Result> methodArgumentNotValidException(MethodArgumentNotValidException ex){
        BindingResult bindingResult = ex.getBindingResult();
        List<ObjectError> allErrors = bindingResult.getAllErrors();
        ObjectError objectError = allErrors.get(0);
        return ResponseEntity.ok(Result.error(objectError.getDefaultMessage()));
    }

    @ExceptionHandler(value = {ConstraintViolationException.class})
    public ResponseEntity<Result> methodArgumentNotValidException(ConstraintViolationException ex){
        return ResponseEntity.ok(Result.error(ex.getMessage()));
    }
}
